#!/usr/bin/python

from xml.dom import minidom
from string import *
import os, sys, time

print time.strftime('%X', time.localtime())
try:
    fp = open(r"topcard20081209_2.xml", "r")
except:
    print "open xml failed"
    sys.exit()

dom = minidom.parse(fp)
root = dom.documentElement
fp.close()

dir = os.environ['APPHOME'] + "/sql/table"
if os.path.exists(dir) != True:
    os.mkdir(dir)
os.chdir(dir)
print time.strftime('%X', time.localtime())

colName = colCode = colType = []
tblDisc = tblName = tblComment = '****'
for oPackage in root.getElementsByTagName("o:Package"):
    for DataNode in oPackage.childNodes:
        '''c:Tables'''
        if DataNode.nodeName == "a:Code" :
            fileNewName = (DataNode.childNodes[0].data + '.txt').lower()
            if os.path.exists(fileNewName):
                os.remove(fileNewName)
            fp_temp = open(fileNewName, 'a+')
        elif DataNode.nodeName == "c:Tables" :
            for tablesNode in DataNode.childNodes :
                ''' c:Tables '''
                tblDisc = tblName = 'Error'
                for tableNode in tablesNode.childNodes :
                    '''o:Table'''
                    if tableNode.nodeName == 'a:Name':
                        tblDisc = tableNode.childNodes[0].data
                    elif tableNode.nodeName == 'a:Code':
                        tblName = tableNode.childNodes[0].data
                    elif tableNode.nodeName == 'a:Comment':
                        tblComment = tableNode.childNodes[0].data
                    elif tableNode.nodeName == 'c:Columns':
                        colName = colCode = colType = []
                        for ColsNode in tableNode.childNodes :
                            ''' c:Columns '''
                            for ColNode in ColsNode.childNodes :
                                if ColNode.nodeName == 'a:Name':
                                    colName.insert(-1, ColNode.childNodes[0].data)
                                elif ColNode.nodeName == 'a:Code':
                                    colCode.insert(-1, ColNode.childNodes[0].data)
                                elif ColNode.nodeName == 'a:DataType':
                                    colType.insert(-1, ColNode.childNodes[0].data)

                if tblName != 'Error':
                    fp_temp.write(tblName + '-'*6 + tblDisc + '-'*6 + tblComment +'\n')
                    #print (tblName + '-'*6 + tblDisc + '-'*6 + tblComment +'\n')
                    i = len(colCode)
                    while i:
                        i -= 1
                        if len(colCode) > 0 and len(colType) > 0 and len(colName) > 0:
                            str = colCode.pop() + ' '*6 + colType.pop() + ' '*6 + colName.pop()
                            fp_temp.write(str +'\n')
                    fp_temp.write('\n\n' + '=' * 30 + '\n')
            fp_temp.close()

print time.strftime('%X', time.localtime())

